package net.xdclass.service.controller;

import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import net.xdclass.service.domain.ProductOrder;
import net.xdclass.service.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * author: 何建文
 * create: 2020-07-18 16:38
 * description:
 **/
@RestController
@RequestMapping("/api/v1/order")
public class OrderController {

    @Autowired
    private OrderService orderService;

    @RequestMapping("/save")
    @HystrixCommand(fallbackMethod = "saveOrderFail")
    public Object save(HttpServletRequest request, int userId, int productId) {
        String token = request.getHeader("token");
        /**
         * 如果网关不将zuul.routes.sensitive-headers这个配置设置为空，那么，初始化的时候，cookie会在网管层过滤掉，
         * 不会传递到后面的服务里面来，服务是获取不到cookie里面的数据的，详情可查看
         * {@link org.springframework.cloud.netflix.zuul.filters.ZuulProperties#getSensitiveHeaders}
         */
        String cookie = request.getHeader("cookie");
        System.out.println(token);
        System.out.println(cookie);


        ProductOrder productOrder = orderService.save(userId, productId);
        Map<String, Object> result = new HashMap<>();
        result.put("code", 0);
        result.put("data", productOrder);
        return result;
    }

    /**
     * 注意方法声明一定要和api一致
     *
     * @param userId
     * @param productId
     * @return
     */
    private Object saveOrderFail(HttpServletRequest request, int userId, int productId) {
        Map<String, Object> result = new HashMap<>();
        result.put("code", -1);
        result.put("msg", "抢购人数太多，你被挤出来了，稍后重试。");
        return result;
    }
}
